package com.exigen.perflabstat.services.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.model.UploadedFile;

import au.com.bytecode.opencsv.CSVReader;

import com.exigen.perflabstat.dao.ProjectNameDao;
import com.exigen.perflabstat.dao.ScenarioDao;
import com.exigen.perflabstat.dao.ScenarioTypeDao;
import com.exigen.perflabstat.dao.TestRawResultsDao;
import com.exigen.perflabstat.dao.TestResultsDao;
import com.exigen.perflabstat.dao.TestSummaryDao;
import com.exigen.perflabstat.dao.TestSummaryDataDao;
import com.exigen.perflabstat.dao.TransactionNameDao;
import com.exigen.perflabstat.models.ProjectName;
import com.exigen.perflabstat.models.Scenario;
import com.exigen.perflabstat.models.ScenarioType;
import com.exigen.perflabstat.models.TestRawResults;
import com.exigen.perflabstat.models.TestResults;
import com.exigen.perflabstat.models.TestSummary;
import com.exigen.perflabstat.models.TestSummaryData;
import com.exigen.perflabstat.models.TransactionName;
import com.exigen.perflabstat.services.Template2Service;


public class Template2ServiceImpl implements Template2Service {

	//DAO fields
	private TestSummaryDataDao testSummaryDataDao;
	private TestResultsDao testResultsDao;
	private ProjectNameDao projectNameDao;
	private ScenarioDao scenarioDao;
	private ScenarioTypeDao scenarioTypeDao;
	private TransactionNameDao transactionNameDao;
	private TestSummaryDao tsd;
	private TestRawResultsDao testRawResultsDao;

	//Models
	private ProjectName projectName = new ProjectName();
	private TestSummary testSummary = new TestSummary();
	private TestSummaryData testSummaryData = new TestSummaryData();
	private TestResults testResults = new TestResults();
	private TransactionName transactionName = new TransactionName();
	
	
	private List<Long> tests = new ArrayList<Long>();
	private String state;
	private String scenario;
	private String scenarioType;
	
	private Long projectId;
	private Integer templateNumber;
	
	private Long transactionNameCount = 0L;
	private Long scenarioCount = 0L;
	private Long scenarioTypeCount = 0L;
	private Long projectNameCount = 0L;
	//private Long transactionTypeCount = 0L;
	private Long testRawResultsCount = 0L;
	private Long testResultsCount = 0L;
	private Long testSummaryCount = 0L;
	private Long testSummaryDataCount = 0L;
	
	//For Test Summary Data
	private Long passTotal = 0L;
	private Long failTotal = 0L;
	private Long stopTotal = 0L;
	
	
	
	//Converts UploadedFile to File
 	public File loadFile(UploadedFile uploadedFile) {	
		File file = null;
		try {
			
			File targetFolder = new File("C:/Users/rfridrihsons/Desktop/test");//TODO
			InputStream inputStream = uploadedFile.getInputstream();

			file = new File(targetFolder, uploadedFile.getFileName());
			
			OutputStream out = new FileOutputStream(file);
			int read = 0;
			byte[] bytes = new byte[1024];

			while ((read = inputStream.read(bytes)) != -1) {
				out.write(bytes, 0, read);
			}
			
			inputStream.close();
			out.flush();
			out.close();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return file;
	}
	
 	
 	//Parse filename data
	public void loadFilenameData(String filename) {
		
    	tests.clear();
		String template = null;
		String branch = null;
		String buildNumber = null;
		
    	template = filename.substring(0, 2);
    	
    	if(template.equals("WL"))templateNumber = 1;
    	if(template.equals("LR"))templateNumber = 2;
    	if(templateNumber == null)templateNumber = 0;

    	//Cut first 3 characters which represented template
    	filename = filename.substring(3);
    	
    	projectName.setPROJECT_NAME(filename.substring(0,filename.indexOf('-')));
    	
    	//Cut project name out of filename
    	filename = filename.substring(filename.indexOf('-')+1);
    	
    	branch = filename.substring(0,filename.indexOf('-'));
    	
    	//Cut branch out of filename
    	filename = filename.substring(filename.indexOf('-')+1);
    	
    	buildNumber = filename.substring(0,filename.length()-4);
    	
    	if(checkIfProjectExists(projectName) == false) {
    		createProject(projectName);
			//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Project added")); 
    	}
    	
    	testSummary.setBRANCH_ID(branch);
    	testSummary.setBUILD_NUMBER(buildNumber);
		testSummary.setPROJECT_ID(projectNameDao.findByProjectName(projectName.getPROJECT_NAME()).getPROJECT_ID());
		
		projectId = testSummary.getPROJECT_ID();
    }
	
	
	//Parse by template1
	public void parseFileTemplate1(File file) {
		
		List<TestRawResults> results = new ArrayList<TestRawResults>();
		List<Double> responses = new ArrayList<Double>();
		
		Double maxResponse = 0.0;
		Double totalResponse = 0.0;
		Double avgResponse = 0.0;
		Double minResponse = 999.9;
		Double percent90 = 0.0;
		Long passCount = 0L;
		Long failCount = 0L;
		Long stopCount = 0L;
		Long totalCount = 0L;

		String previousName = null;
		
			try {
				CSVReader in = new CSVReader(new FileReader(file));
				
				String [] line;
				
				while ((line = in.readNext()) != null) {
					TestRawResults result = new TestRawResults();
					
					java.sql.Timestamp timestamp = null;
					try {
						SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						java.util.Date parsedDate = dateFormat.parse(line[0]);
						timestamp = new java.sql.Timestamp(parsedDate.getTime());
					} catch (ParseException e) {
						e.printStackTrace();
					}
					result.setTRANSACTIONSTART(timestamp);
					if(testSummary.getSTARTTIME() == null)
						testSummary.setSTARTTIME(timestamp);
					result.setVIRTUALUSER_NUMBER(Long.parseLong(line[1]));
					result.setName(line[2]);
					
					result.setRESPONSE_TIME(Double.parseDouble(line[3]));
					
					result.setRESPONSECODE(line[4]);
					
					if(line.length > 5)
						result.setRESPONSE_SIZE(Long.parseLong(line[5]));
					else
						result.setRESPONSE_SIZE(0L);
					result.setRESPONSE_MESSAGE("no message");
					
					
					results.add(result);
				}
				
				in.close();
				
				//Sort raw test data
				Collections.sort(results, new Comparator<TestRawResults>() {
					public int compare(final TestRawResults object1, final TestRawResults object2) {
			            return object1.getName().compareTo(object2.getName());
			        }
			       } );
				
				int resultIndex = 0;
				
				//Parse sorted list
				for(TestRawResults result: results) {
					
					//<State>_<Scenario>_<Scenario Type>_<Transaction Name>
					//AZ_PolicyIssue_2D2V_001_Launch_App_Home_Page
					
					String name = result.getName();
					
					if(!name.equals(previousName)) {
						
						if(previousName != null) {
							//Deal with previous test results
							//Transaction Name,SLA Status,Minimum,Average,Maximum,Std. Deviation,90 Percent,Pass,Fail,Stop,,,,,,,,,
							//AZ_PolicyIssue_2D2V_001_Launch_App_Home_Page,No Data,0.01,0.598,3.421,0.782,1.98,109,0,0,,,,,,,,,
							
							//testResults.setTRANSACTION_ID(transactionName.getTRANSACTION_ID()); done in transaction name
							//testResults.setTESTSUMMARY_ID(testSummary.getTESTSUMMARY_ID()); done in test summary
							avgResponse = totalResponse / totalCount;
							
							if(responses.size() > 0)
								percent90 = responses.get(responses.size() - responses.size()/10);
							testResults.setAPDEX(calculateApdex(responses));
							
							/*
							testResults.setPASS_COUNT(passCount);
							testResults.setFAIL_COUNT(failCount);
							testResults.setSTOP_COUNT(stopCount);
							
							if(!checkIfTestResultExists(testResults))
								createTestResults(testResults);
								*/
							
							String[] line1 = new String[10];
							line1[0] = result.getName();
							line1[1] = percent90.toString();
							line1[2] = minResponse.toString();
							line1[3] = avgResponse.toString();
							line1[4] = maxResponse.toString();
							line1[5] = calculateDeviation(responses, avgResponse).toString();
							line1[6] = responses.get(responses.size() - responses.size()/10).toString();
							line1[7] = passCount.toString();
							line1[8] = failCount.toString();
							line1[9] = stopCount.toString();
							
							transactionParse(line1);
							
							
							//Restart counters
							maxResponse = 0.0;
							totalResponse = 0.0;
							minResponse = 999.9;
							percent90 = 0.0;
							//deviation = 0.0;
							passCount = 0L;
							failCount = 0L;
							stopCount = 0L;
							totalCount = 0L;
							responses.clear();
							
						}
						
						state = name.substring(0, 2);

				    	//Cut first 3 characters which represented state
						name = name.substring(3);
				    	
				    	scenario = name.substring(0,name.indexOf('-'));
				    	
				    	//Cut scenario out of string
				    	name = name.substring(name.indexOf('-')+1);

				    	scenarioType = name.substring(0,name.indexOf('_'));
				    	
				    	//Cut scenario type out of filename
				    	name = name.substring(name.indexOf('_')+1);
				    	
				    	result.setTRANSACTION_NAME(name);
				    	
				    	if(checkIfScenarioExists(scenario) == false) {
				    		Scenario newScenario = new Scenario();
				    		newScenario.setSCENARIO_NAME(scenario);
				    		newScenario.setCOMMENTS("");
				    		createScenario(newScenario);
				    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Scenario added"));
				    	}
				    	
				    	if(checkIfScenarioTypeExists(scenarioType) == false) {
				    		ScenarioType newScenarioType = new ScenarioType();
				    		newScenarioType.setSCENARIO_TYPE_NAME(scenarioType);
				    		newScenarioType.setCOMMENTS("");
				    		createScenarioType(newScenarioType);
				    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Scenario Type added"));
				    	}
				    	
				    	transactionName.setPROJECT_ID(projectId);
				    	transactionName.setSCENARIO_ID(scenarioDao.findByScenarioName(scenario).getSCENARIO_ID());
				    	transactionName.setSCENARIO_TYPE_ID(scenarioTypeDao.findByScenarioType(scenarioType).getSCENARIO_TYPE_ID());
				    	transactionName.setTRANSACTION_TYPE_ID(6L);//todo
				    	transactionName.setTRANSACTION_NAME(name);
				    	transactionName.setSLA_VALUE(3.0);//todo
				    	transactionName.setCOMMENTS("");
				    	
				    	if(checkIfTransactionNameExists(transactionName.getTRANSACTION_NAME()) == false) {
				    		createTransactionName(transactionName);
				    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Transaction Name added"));
				    	}
				    	else {
				    		testResults.setTRANSACTION_ID(transactionNameDao.findByTransactionName(name).getTRANSACTION_ID());
				    	}
				    	
				    	
				    	testSummary.setSCENARIO_ID(scenarioDao.findByScenarioName(scenario).getSCENARIO_ID());
				    	testSummary.setSCENARIO_TYPE_ID(scenarioTypeDao.findByScenarioType(scenarioType).getSCENARIO_TYPE_ID());
				    	testSummary.setSTATE(state);
				    	testSummary.setBASELINE('0');//todo
				    	if(!checkIfTestSummaryExists(testSummary)) {
				    		createTestSummary(testSummary);
				    	}
				    	else {
				    		testResults.setTESTSUMMARY_ID(tsd.checkIfExists(testSummary).getTESTSUMMARY_ID());
				    	}
				    	
				    	int i = resultIndex-1;
				    	for(i=resultIndex-1; i>0 && results.get(i).getName().equals(results.get(i-1).getName()); i--) {
							
				    		results.get(i).setTRANSACTION_ID(testResults.getTRANSACTION_ID());
				    		if(checkIfTestRawResultsExist(results.get(i)) == false) {
				    			testRawResultsDao.save(results.get(i));
				        		testRawResultsCount++;
				    		}
				    	}
				    	//Last one
				    	if(i >= 0) {
				    		results.get(i).setTRANSACTION_ID(testResults.getTRANSACTION_ID());
				    		if(checkIfTestRawResultsExist(results.get(i)) == false) {
				    			testRawResultsDao.save(results.get(i));
				    			testRawResultsCount++;
				    		}
				    	}
			
					}
					
					//Count response times for calculations
					if(result.getRESPONSE_TIME() > maxResponse)
						maxResponse = result.getRESPONSE_TIME();
					totalResponse += result.getRESPONSE_TIME(); 
					if(result.getRESPONSE_TIME() < minResponse)
						minResponse = result.getRESPONSE_TIME();
					
					//Count responses
					if(result.getRESPONSECODE().equals("Success"))
						passCount++;
					if(result.getRESPONSECODE().equals("Stop"))
						stopCount++;
					if(result.getRESPONSECODE().equals("Fail"))
						failCount++;
					
					totalCount++;
					
					previousName = result.getName();
					responses.add(result.getRESPONSE_TIME());
					
					resultIndex++;
				}
					
					
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		printCounters();
	}
	
	
	//PrimeFace messages
	public void printCounters() {

		if(transactionNameCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(transactionNameCount.toString() + " New Transaction Names added"));
		
		if(scenarioCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(scenarioCount.toString() + " New Scenarios added"));
		
		if(scenarioTypeCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(scenarioTypeCount.toString() + " New Scenario Types added"));
		
		if(projectNameCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(projectNameCount.toString() + " New Projects added"));
		
		if(testRawResultsCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(testRawResultsCount.toString() + " New Raw Test Results added"));
		
		if(testResultsCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(testResultsCount.toString() + " New Test Results added"));
		
		if(testSummaryCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(testSummaryCount.toString() + " New Test Summaries added"));
		
		if(testSummaryDataCount > 0)
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(testSummaryDataCount.toString() + " New Test Summary Data added"));
	}
	
	
	//Check if test raw exists in database
	public boolean checkIfTestRawResultsExist(TestRawResults t) {
		if(testRawResultsDao.checkIfExists(t) != null)
			return true;
		else
			return false;
	}
	
	
	
	public Double calculateApdex(List<Double> responses) {
		Double toleratedValue = transactionName.getSLA_VALUE();
		Double frustratedValue = 4 * toleratedValue;
		Double apdex = 0.0;
		for(Double response: responses) {
			if(response <= toleratedValue)
				apdex += response;
			else if(response <= frustratedValue)
				apdex+= response * 0.5;
		}
		apdex /= responses.size();
		return apdex;
	}
	
	public Double calculateDeviation(List<Double> responses, Double avgResponse) {
		Double deviation = 0.0;
		for(Double response: responses) {
			deviation += (response-avgResponse) * (response-avgResponse);
		}
		deviation /= responses.size();
		deviation = Math.sqrt(deviation);
		return deviation;
	}

	public boolean parseFileTemplate2(File file) {
		
		String comments = "";
		String duration = null;
		//Float throughputTotal = null; same as hits total
		//Float throughputAverage = null; same as hits average
		Double hitsTotal = null;
		Double hitsAverage = null;
		
		boolean isTransaction = false;
		boolean isHttp = false;
		

		try {
			CSVReader in = new CSVReader(new FileReader(file));
			
			String [] line;
			
			while ((line = in.readNext()) != null) {
				
				
				if(line[0].equals("")) {
					if(isTransaction)isTransaction = false;
					if(isHttp)isHttp = false;
					continue;
				}
				
				
				if(line[0].equals("Analysis Summary")) {
					try {
						line[2] = line[2].substring(line[2].indexOf(' ')+1);
						DateFormat date = new SimpleDateFormat("dd/MM/yyyy");
						DateFormat time = new SimpleDateFormat("HH:mm:ss");
						
						Date date1 = date.parse(line[2].substring(0, line[2].indexOf(' ')));
						line[2] = line[2].substring(13);
						Date time1 = time.parse(line[2].substring(0, line[2].indexOf(' ')));
						Timestamp startTime = new Timestamp(date1.getTime() + time1.getTime());
						line[2] = line[2].substring(11);
						Date date2 = date.parse(line[2].substring(0, line[2].indexOf(' ')));
						line[2] = line[2].substring(13);
						Date time2 = time.parse(line[2]);
						Timestamp endTime = new Timestamp(date2.getTime() + time2.getTime());
						
						Long dur = Math.abs(startTime.getTime() - endTime.getTime());
						duration = String.format("%02d:", TimeUnit.MILLISECONDS.toDays(dur));

						duration = duration.concat(String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(dur)%24, TimeUnit.MILLISECONDS.toMinutes(dur)%60, TimeUnit.MILLISECONDS.toSeconds(dur)%60));
								
						testSummary.setSTARTTIME(startTime);
						testSummaryData.setENDTIME(endTime);
						testSummaryData.setDURATION(duration);
						
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
				
				
				if(line[0].equals("Maximum Running Vusers:")) {
					testSummaryData.setMAX_VIRTUALUSERS(Integer.parseInt(line[2]));
				}
				
				/*if(line[0].equals("Total Throughput (bytes):")) {
					line[2] = line[2].replaceAll(",", "");
					throughputTotal = Float.parseFloat(line[2]);
				}*/
				
				/*if(line[0].equals("Average Throughput (bytes/second):")) {
					line[2] = line[2].replaceAll(",", "");
					throughputAverage = Float.parseFloat(line[2]);
				}*/
				
				if(line[0].equals("Total Hits:")) {
					line[2] = line[2].replaceAll(",", "");
					hitsTotal = Double.parseDouble(line[2]);
				}
				
				if(line[0].equals("Average Hits per Second:")) {
					hitsAverage = Double.parseDouble(line[2]);
				}
				
				if(line[0].equals("Scenario Name:")) {
					//scenario1 = line[1];
				}
				
				/* if(line[0].equals("Transactions:")) {
					line[2] = line[2].replaceAll(",", "");
					passTotal = Integer.parseInt(line[2]);
					
					line[4] = line[4].replaceAll(",", "");
					failTotal = Integer.parseInt(line[4]);
				
					line[6] = line[6].replaceAll(",", "");
					stopTotal = Integer.parseInt(line[6]);
				} */
				
				if(isTransaction)
					transactionParse(line);
				if(isHttp)
					httpParse(line);
				
				if(line[0].equals("HTTP Responses"))
					isHttp = true;
				
				if(line[0].equals("Transaction Name") && line[1].equals("SLA Status")) {
					
					//testSummaryData.setTESTSUMMARY_ID(q);tbd
					//testSummaryData.setDURATION(duration); done
					//testSummaryData.setENDTIME(endTime); done
					//testSummaryData.setMAX_VIRTUAL_USERS(vusers); done
					testSummaryData.setTHROUGHPUT_TOTAL(hitsTotal);
					testSummaryData.setTHROUGHPUT_AVERAGE(hitsAverage);
					testSummaryData.setHITS_AVERAGE_PER_SECOND(hitsAverage);
					testSummaryData.setHITS_TOTAL(hitsTotal);
					testSummaryData.setHTTP_RESPONSE_PER_SECOND(hitsAverage);
					testSummaryData.setHTTP_RESPONSE_TOTAL(hitsTotal);
					//testSummaryData.setPASS_TOTAL(passTotal); TODO
					//testSummaryData.setFAIL_TOTAL(failTotal); TODO
					//testSummaryData.setSTOP_TOTAL(stopTotal); TODO
					testSummaryData.setOVERALSTATUS('0');
					testSummaryData.setBASELINE('0');//tbd
					testSummaryData.setCOMMENTS(comments);
					
					isTransaction = true;
				}
				
			}
			
			
			in.close();
			
			if(passTotal + failTotal + stopTotal > 0) {
				testSummaryData.setPASS_TOTAL(passTotal);
				testSummaryData.setFAIL_TOTAL(failTotal);
				testSummaryData.setSTOP_TOTAL(stopTotal);
				if(!checkIfTestSummaryDataExists(testSummaryData))
					createTestSummaryData(testSummaryData);
				
				passTotal = 0L;
				failTotal = 0L;
				stopTotal = 0L;
				testSummaryData.setOVERALSTATUS('0');
    		}
			
			for(Long testId: tests) {
				TestSummaryData newtsd = testSummaryData;
				newtsd.setTESTSUMMARY_ID(testId);
				createTestSummaryData(newtsd);
				//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Test Summary Data added"));
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		
		printCounters();
		return true;
	}
	
	public void httpParse(String[] line) {
		//HTTP Responses,Total,Per second
		//HTTP_200,"82,519",21.501
		
		line[1] = line[1].replaceAll(",", "");
		Double total = testSummaryData.getHTTP_RESPONSE_TOTAL();
		testSummaryData.setHTTP_RESPONSE_TOTAL(Double.parseDouble(line[1]) + ((total == null)?0:total));
		
		Double perSecond = testSummaryData.getHTTP_RESPONSE_PER_SECOND();
		testSummaryData.setHTTP_RESPONSE_PER_SECOND(Double.parseDouble(line[2]) + ((perSecond == null)?0:perSecond));
	}
	
	public void transactionParse(String[] line) {
		//Transaction Name,SLA Status,Minimum,Average,Maximum,Std. Deviation,90 Percent,Pass,Fail,Stop,,,,,,,,,
		//AZ_PolicyIssue_2D2V_001_Launch_App_Home_Page,No Data,0.01,0.598,3.421,0.782,1.98,109,0,0,,,,,,,,,
		transactionNameParse(line[0]);
		
		Character slaStatus;
		Double minResponse = Double.parseDouble(line[2]);
		Double avgResponse = Double.parseDouble(line[3]);
		Double maxResponse = Double.parseDouble(line[4]);
		Double deviation = Double.parseDouble(line[5]);
		Double percent90 = Double.parseDouble(line[6]);
		Long pass = Long.parseLong(line[7]);
		Long fail = Long.parseLong(line[8]);
		Long stop = Long.parseLong(line[9]);
		passTotal += pass;
		
		//String comments = "";
		
		if(transactionName.getSLA_VALUE() != null)
			if(percent90 > transactionName.getSLA_VALUE())
				slaStatus = '1';
			else 
				slaStatus = '0';
		else
			if(percent90 > 3.0)
				slaStatus = '1';
			else
				slaStatus = '0';
		
		if(slaStatus.equals('0'))
			testSummaryData.setOVERALSTATUS('1');
		
		//testResults.setTRANSACTION_ID() done in transaction name
		//testResults.setTESTSUMMARY_ID() done in test summary
		testResults.setMAX_RESPONSE(maxResponse);
		testResults.setAVERAGE_RESPONSE(avgResponse);
		testResults.setMINIMUM_RESPONSE(minResponse);
		testResults.setPERCENT90(percent90);
		testResults.setDEVIATION(deviation);
		if(testResults.getAPDEX() == null)
			testResults.setAPDEX(0.0);
		testResults.setPASS_COUNT(pass);
		testResults.setFAIL_COUNT(fail);
		testResults.setSTOP_COUNT(stop);
		if(testResults.getSLA_STATUS() == null)
			testResults.setSLA_STATUS('0');
		//testResults.setCOMMENTS("");
		
		if(checkIfTestResultExists(testResults) == false) {
			createTestResults(testResults);
		}
		
		
	}
	
	public void transactionNameParse(String name) {
		//<State>_<Scenario>_<Scenario Type>_<Transaction Name>
		//AZ_PolicyIssue_2D2V_001_Launch_App_Home_Page
		
		if (name == null) return;
		
		boolean needNewTestSummary = false;
		
		if(!name.substring(0, 2).equals(state)) {
			needNewTestSummary = true;
			state = name.substring(0, 2);
		}

    	//Cut first 3 characters which represented state
		name = name.substring(3);
    	
		int i = Math.min(name.indexOf('_'), name.indexOf('-'));
		if(i < 0)
			i = Math.max(name.indexOf('_'), name.indexOf('-'));
		
    	if(!name.substring(0,i).equals(scenario)) {
    		needNewTestSummary = true;
    		scenario = name.substring(0,i);
    	}
    	
    	//Cut scenario out of string
    	name = name.substring(i+1);
    	
    	if(!name.substring(0,name.indexOf('_')).equals(scenarioType)) {
    		needNewTestSummary = true;
    		scenarioType = name.substring(0,name.indexOf('_'));
    	}
    	
    	//Cut scenario type out of filename
    	name = name.substring(name.indexOf('_')+1);
    	
    	//transactionName = name; tbd
    	
    	if(checkIfScenarioExists(scenario) == false) {
    		Scenario newScenario = new Scenario();
    		newScenario.setSCENARIO_NAME(scenario);
    		newScenario.setCOMMENTS("");
    		createScenario(newScenario);
    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Scenario added"));
    	}
    	
    	if(checkIfScenarioTypeExists(scenarioType) == false) {
    		ScenarioType newScenarioType = new ScenarioType();
    		newScenarioType.setSCENARIO_TYPE_NAME(scenarioType);
    		newScenarioType.setCOMMENTS("");
    		createScenarioType(newScenarioType);
    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Scenario Type added"));
    	}
    	
    	transactionName.setPROJECT_ID(projectId);
    	transactionName.setSCENARIO_ID(scenarioDao.findByScenarioName(scenario).getSCENARIO_ID());
    	transactionName.setSCENARIO_TYPE_ID(scenarioTypeDao.findByScenarioType(scenarioType).getSCENARIO_TYPE_ID());
    	transactionName.setTRANSACTION_TYPE_ID(6L);//tbd
    	transactionName.setTRANSACTION_NAME(name);
    	transactionName.setSLA_VALUE(3.0);//tbd
    	transactionName.setCOMMENTS("");
    	
    	if(checkIfTransactionNameExists(transactionName.getTRANSACTION_NAME()) == false) {
    		createTransactionName(transactionName);
    		//FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("New Transaction Name added"));
    	}
    	else {
    		testResults.setTRANSACTION_ID(transactionNameDao.findByTransactionName(name).getTRANSACTION_ID());
    	}
    	
    	if(needNewTestSummary) {
    		testSummary.setSCENARIO_ID(scenarioDao.findByScenarioName(scenario).getSCENARIO_ID());
    		testSummary.setSCENARIO_TYPE_ID(scenarioTypeDao.findByScenarioType(scenarioType).getSCENARIO_TYPE_ID());
    		testSummary.setSTATE(state);
    		testSummary.setBASELINE('0');//tbd
    		if(!checkIfTestSummaryExists(testSummary)) {
    			createTestSummary(testSummary);
    		}
    		
    		if(passTotal + failTotal + stopTotal > 0) {
				testSummaryData.setPASS_TOTAL(passTotal);
				testSummaryData.setFAIL_TOTAL(failTotal);
				testSummaryData.setSTOP_TOTAL(stopTotal);
				if(!checkIfTestSummaryDataExists(testSummaryData))
					createTestSummaryData(testSummaryData);
				
				//Reset counters
				passTotal = 0L;
				failTotal = 0L;
				stopTotal = 0L;
				testSummaryData.setOVERALSTATUS('0');
    		}
    		
    		testSummaryData.setTESTSUMMARY_ID(tsd.checkIfExists(testSummary).getTESTSUMMARY_ID());
    	}
    	else {
    		testResults.setTESTSUMMARY_ID(tsd.checkIfExists(testSummary).getTESTSUMMARY_ID());
    	}
    	
	}
	
	public boolean checkIfTestSummaryDataExists(TestSummaryData testSummaryData) {
		if(testSummaryDataDao.checkIfExists(testSummaryData) != null)
			return true;
		else 
			return false;
	}
	
	public void createTestSummaryData(TestSummaryData testSummaryData) {
		TestSummaryData newTestSummaryData = new TestSummaryData();
		newTestSummaryData = testSummaryData;
		testSummaryDataDao.save(newTestSummaryData);
		testSummaryDataCount++;
	}
	
	public boolean checkIfTestResultExists(TestResults testResults) {
		if(testResultsDao.checkIfExists(testResults) != null)
			return true;
		else 
			return false;
	}
	
	public void createTestResults(TestResults testResults) {
		TestResults testResults1 = testResults;
		testResultsDao.save(testResults1);
		testResultsCount++;
	}
	
	public boolean checkIfTestSummaryExists(TestSummary testSummary) {
		TestSummary test = tsd.checkIfExists(testSummary);
		
		if(test != null) {
			testResults.setTESTSUMMARY_ID(test.getTESTSUMMARY_ID());
			return true;
		}
		else return false;
	}
	
	public void createTestSummary(TestSummary testSummary) {
		TestSummary newTestSummary = testSummary;
		newTestSummary.setTESTSUMMARY_ID(null);
		
		Long testSummaryId = tsd.save(newTestSummary).getTESTSUMMARY_ID();
		tests.add(testSummaryId);
		testResults.setTESTSUMMARY_ID(testSummaryId);
		testSummaryCount++;
	}
	
	public boolean checkIfTransactionNameExists(String transactionName) {
		if(transactionNameDao.findByTransactionName(transactionName) != null) return true;
		else return false;
	}
	
	public void createTransactionName(TransactionName transactionName) {
		TransactionName newTransactionName = transactionName;
		newTransactionName.setTRANSACTION_ID(null);
		testResults.setTRANSACTION_ID(transactionNameDao.save(newTransactionName).getTRANSACTION_ID());
		transactionNameCount++;
	}
	
	public boolean checkIfScenarioTypeExists(String scenarioType) {
		if(scenarioTypeDao.findByScenarioType(scenarioType) != null) return true;
		else return false;
	}
	
	public void createScenarioType(ScenarioType scenarioType) {
		ScenarioType newScenarioType = new ScenarioType();
		newScenarioType = scenarioType;
		scenarioTypeDao.save(newScenarioType);
		scenarioTypeCount++;
	}
	
	public boolean checkIfScenarioExists(String scenario) {
		if(scenarioDao.findByScenarioName(scenario) != null) return true;
		else return false;
	}
	
	public void createScenario(Scenario scenario) {
		Scenario newScenario = new Scenario();
		newScenario = scenario;
		scenarioDao.save(newScenario);
		scenarioCount++;
	}
	
	public boolean checkIfProjectExists(ProjectName projectName) {
		if(this.projectNameDao.findByProjectName(projectName.getPROJECT_NAME()) != null) return true;
		else return false;
	}
	
	public void createProject(ProjectName projectName) {
		ProjectName newProject = new ProjectName();
		newProject = projectName;
		this.projectNameDao.save(newProject);
		projectNameCount++;
	}
	
	
	
	//Getters and Setters ----------------------------------------------------------------------------------------------------------
	
	
	
	public TestResultsDao getTestResultsDao() {
		return testResultsDao;
	}

	public void setTestResultsDao(TestResultsDao testResultsDao) {
		this.testResultsDao = testResultsDao;
	}

	public ScenarioDao getScenarioDao() {
		return scenarioDao;
	}

	public void setScenarioDao(ScenarioDao scenarioDao) {
		this.scenarioDao = scenarioDao;
	}

	public ProjectNameDao getProjectNameDao() {
		return projectNameDao;
	}

	public void setProjectNameDao(ProjectNameDao projectNameDao) {
		this.projectNameDao = projectNameDao;
	}

	public ScenarioTypeDao getScenarioTypeDao() {
		return scenarioTypeDao;
	}

	public void setScenarioTypeDao(ScenarioTypeDao scenarioTypeDao) {
		this.scenarioTypeDao = scenarioTypeDao;
	}

	public TransactionNameDao getTransactionNameDao() {
		return transactionNameDao;
	}

	public void setTransactionNameDao(TransactionNameDao transactionNameDao) {
		this.transactionNameDao = transactionNameDao;
	}

	public TestSummaryDao getTsd() {
		return tsd;
	}

	public void setTsd(TestSummaryDao tsd) {
		this.tsd = tsd;
	}

	public Integer getTemplateNumber() {
		return templateNumber;
	}

	public void setTemplateNumber(Integer templateNumber) {
		this.templateNumber = templateNumber;
	}

	public TestSummaryDataDao getTestSummaryDataDao() {
		return testSummaryDataDao;
	}

	public void setTestSummaryDataDao(TestSummaryDataDao testSummaryDataDao) {
		this.testSummaryDataDao = testSummaryDataDao;
	}

	public TestRawResultsDao getTestRawResultsDao() {
		return testRawResultsDao;
	}

	public void setTestRawResultsDao(TestRawResultsDao testRawResultsDao) {
		this.testRawResultsDao = testRawResultsDao;
	}

}
